#include "infoinquire.h"
#include "ui_infoinquire.h"
#include <QDebug>
#include <QMessageBox>
#include <QLabel>
#include <QMouseEvent>
#include <QUrlQuery>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDateTime>



InfoInquire::InfoInquire(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::InfoInquire)
{

    ui->setupUi(this);

    //事件过滤函数(键盘)的开启
    softKeyboard = new SoftKeyboard();
    //信息窗口点击事件处理
    ui->lineEdit->installEventFilter(this);
    networkManager = new QNetworkAccessManager(this);
    connect(ui->tableWidget,&QTableWidget::cellClicked,this,&InfoInquire::onCellClicked);
    connect(networkManager, &QNetworkAccessManager::finished, this, &InfoInquire::Received);

    //查询数据库，初始化界面信息
    QString  mapUrl = "http://192.168.1.117:8080/api/records";
    QUrl url(mapUrl);
    QNetworkRequest request(url);
    networkManager->get(request);

    QString parkingmapUrl = "http://192.168.1.117:8080/api/parking_spots";
    QUrl parkingurl(parkingmapUrl);
    QNetworkRequest parkrequest(parkingurl);
    networkManager->get(parkrequest);




}


InfoInquire::~InfoInquire()
{
    delete ui;
}



//刷新,发送查询记录请求
void InfoInquire::on_pushButton_clicked()
{
    //发送记录请求查询
    QString  mapUrl = "http://192.168.1.117:8080/api/records";

    QUrl url(mapUrl);
    //执行命令
    QNetworkRequest request(url);
    networkManager->get(request);

    QString parkingmapUrl = "http://192.168.1.117:8080/api/parking_spots";
    QUrl parkingurl(parkingmapUrl);
    QNetworkRequest parkrequest(parkingurl);
    networkManager->get(parkrequest);
}

void InfoInquire::Received(QNetworkReply *reply)
{
    row = 0;
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray Data = reply->readAll();
        qDebug() << "完整的响应内容: " << QString::fromUtf8(Data);
        QJsonParseError jsonerror;
        QJsonDocument doc = QJsonDocument::fromJson(Data, &jsonerror);
        if(jsonerror.error != QJsonParseError::NoError) //判断是否json格式错误
        {
             qDebug()<<"json error";
        }

        //把doc转对象
        QJsonObject obj = doc.object();
        int  count = obj.value("count").toInt();
        qDebug() << "Count:" << count;

        //如果是车位查询
        if(obj.contains("spots") && obj["spots"].isArray())
        {
            int number=0;
            QJsonArray records = obj["spots"].toArray();
            // 遍历spots数组
            for (const QJsonValue &recordValue : records)
            {

                if (recordValue.isObject())
                {
                    QJsonObject recordObj = recordValue.toObject();
                    int status = recordObj.value("status").toInt();
                    if(status==0)
                    {
                        number++;
                    }
                }
            }
            ui->label->setText(QString::number(number));
            return ;
        }

        //如果是历史查询
        if (obj.contains("records") && obj["records"].isArray())
        {
            QJsonArray records = obj["records"].toArray();
            // 遍历records数组
             for (const QJsonValue &recordValue : records)
             {
                 row++;
                 if (recordValue.isObject())
                 {
                    QJsonObject recordObj = recordValue.toObject();
                    // 提取记录中的字段
                    license_plate = recordObj.value("license_plate").toString();
                    curr_status = recordObj.value("curr_status").toInt();
                    spot_id = recordObj.value("spot_id").toString();
                    enter_time = recordObj.value("enter_time").toString();
                    enter_driver = recordObj.value("enter_driver").toString();
                    exit_driver = recordObj.value("exit_driver").toString();
                    exit_time = recordObj.value("exit_time").toString();
                    cost=recordObj.value("cost").toInt();
                    qDebug() <<"License Plate:" << license_plate;

                    //添加数据信息到tablewidget
                    InTableSelect();
                 }
             }
             // 调整列宽以适应内容
             ui->tableWidget->resizeColumnsToContents();
        }

        // 检查是否查询成功
        if (row == 0)
        {
            //清空tablewidget
            QMessageBox::warning(this,"sql","没有数据");
            ui->tableWidget->clearContents();
            ui->tableWidget->setRowCount(0);
            ui->tableWidget->setColumnCount(0);
        }
    }

    //获取数据失败
    else
    {
        qDebug() << "错误: " << reply->errorString();
        qDebug() << "响应: " << reply->readAll();
    }

    //清空缓存区
    reply->deleteLater();
}

//执行搜查函数并添加到tablewidget
void InfoInquire::InTableSelect()
{
    //设置行数不可见
    QHeaderView *verticalHeader = ui->tableWidget->verticalHeader();
    // 设置垂直头视图为不可见
    verticalHeader->setVisible(false);
    //设置列数
    ui->tableWidget->setColumnCount(8);
    //定义列表标题
    QStringList headers;
    headers<<"车牌号"<<"车辆状态"<<"停车地点"<<"入库时间"<<"进入设备"<<"退出设备"<<"出库时间"<<"停车费用";
    ui->tableWidget->setHorizontalHeaderLabels(headers);

    qint64 in_time = enter_time.toLongLong();
    QDateTime indatetime;
    indatetime= QDateTime::fromTime_t(static_cast<time_t>(in_time));
    QString  m_intime = indatetime.toString("yyyy-MM-dd HH:mm:ss");

    qint64 timestamp = exit_time.toLongLong();
    QDateTime datetime;
    datetime= QDateTime::fromTime_t(static_cast<time_t>(timestamp));
    QString  m_time = datetime.toString("yyyy-MM-dd HH:mm:ss");


    //给每列信息写入数据
    ui->tableWidget->setRowCount(row);
    QTableWidgetItem *item = new QTableWidgetItem(license_plate);

    ui->tableWidget->setItem(row-1,0,item);

    //根据读出数据得出汽车状态
    if(curr_status==1)
    {
        item = new QTableWidgetItem("在库中");
        ui->tableWidget->setItem(row-1,1,item);
    }
    else if(curr_status==0)
    {
        item = new QTableWidgetItem("不在库中");
        ui->tableWidget->setItem(row-1,1,item);
    }

    item = new QTableWidgetItem(spot_id);
    ui->tableWidget->setItem(row-1,2,item);

    item = new QTableWidgetItem(m_intime);
    ui->tableWidget->setItem(row-1,3,item);

    item = new QTableWidgetItem(enter_driver);
    ui->tableWidget->setItem(row-1,4,item);

    item = new QTableWidgetItem(exit_driver);
    ui->tableWidget->setItem(row-1,5,item);

    item = new QTableWidgetItem(m_time);
    ui->tableWidget->setItem(row-1,6,item);

    item = new QTableWidgetItem(QString::number(cost));
    ui->tableWidget->setItem(row-1,7,item);


}


//显示点击地方的详细信息
void InfoInquire::onCellClicked(int row, int column)
{
    // 获取点击单元格的项，并把项中详细内容显示出来
    for(int i=0;i<8;i++)
    {
        QTableWidgetItem *item = ui->tableWidget->item(row, i);
        if (i==0)
        {
            ui->label_13->setText(item->text());
        }
        else if(i==1)
        {
            ui->label_6->setText(item->text());
        }
        else if(i==2)
        {
            ui->label_8->setText(item->text());
        }
        else if(i==3)
        {
            ui->label_10->setText(item->text());
        }
        else if(i==4)
        {
            ui->label_12->setText(item->text());
        }
        else if(i==5)
        {
            ui->label_15->setText(item->text());
        }
        else if(i==6)
        {
            ui->label_17->setText(item->text());
        }
        else if(i==7)
        {
            ui->label_21->setText(item->text());
        }
    }
}





void InfoInquire::on_pushButton_2_clicked()
{
    //发送记录请求查询
    QString  mapUrl = "http://192.168.1.117:8080/api/records";

    QUrl url(mapUrl);
    QUrlQuery query;
    if(ui->lineEdit->text().isEmpty())
    {
          QMessageBox::warning(this,"警告","请输入数据");
    }
    else
    {
        query.addQueryItem("license_plate", ui->lineEdit->text());
        //执行命令
        url.setQuery(query);
        QNetworkRequest request(url);
        networkManager->get(request);
    }


}



//事件过滤器处理函数(键盘)
bool InfoInquire::eventFilter(QObject *watched, QEvent *event)
{
    //添加键盘
    if(event->type()==QEvent::MouseButtonRelease)//事件类型
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);//将事件强制转换
        if(mouseEvent->button() == Qt::LeftButton)
        {
            QPoint point = this->pos();
            if(watched == ui->lineEdit)
            {
                softKeyboard->hideInputBufferArea(ui->lineEdit);
                softKeyboard->resize(600,320);


                // 获取lineEdit的全局位置
                QPoint lineEditGlobalPos = ui->lineEdit->mapToGlobal(QPoint(0, 0));
                // 计算softKeyboard的顶部位置
                int newY = lineEditGlobalPos.y() +ui->lineEdit->height();
                // 移动softKeyboard到lineEdit的上方
                softKeyboard->move(point.x() + (this->width() - 600) / 2, newY);
                softKeyboard->setMoveEnabled(false);
                softKeyboard->show();
            }

        }


    }
    return QMainWindow::eventFilter(watched,event);//返回父类的事件过滤器
}


